package airport.server.DAO;


import airport.server.pojo.User;
import airport.shared.beans.UserBean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Romain on 13/02/15.
 */
public class UserDAO extends DAO<UserBean> {

	@SuppressWarnings("unchecked")
	public ArrayList<UserBean> selectAll() {
		List<User> userList;
		ArrayList<UserBean> userBeanList = new ArrayList<UserBean>();
		User user;

		connection();
		userList = session.createQuery("from User").list();
		commitAndClose();

		Iterator i = userList.iterator();
		while (i.hasNext()) {
			user = (User) i.next();
			userBeanList.add(pojoToBean(user));
		}

		return userBeanList;
	}

	@Override
	public String save(UserBean u) {
		connection();
		session.save(u);
		commitAndClose();

		return "Utilisateur enregistré";
	}

	@Override
	public String update(UserBean u) {
		connection();
		session.update(beanToPojo(u));
		commitAndClose();

		return "Utilisateur mis à jour";
	}

	@Override
	public String delete(UserBean u) {
		connection();
		session.delete(beanToPojo(u));
		commitAndClose();

		return "Utilisateur supprimé";
	}

	public UserBean connexion(String e, String pw) {
        List userList;
        UserBean userBean;
        User user;

        connection();
        userList = session.createQuery("from User p where p.email ='" + e + "' AND p.password ='" + pw + "'").list();

        if (userList != null && userList.size() != 0) {
            user = (User) userList.get(0);
            userBean = pojoToBean(user);
        } else {
            userBean = null;
        }

        commitAndClose();

        return userBean;
    }

	private UserBean pojoToBean(User user) {
		UserBean userBean = new UserBean();
		userBean.setEmail(user.getEmail());
		userBean.setPw(user.getPassword());
        userBean.setNom(user.getNom());
        userBean.setPrenom(user.getPrenom());

		return userBean;
	}

	private User beanToPojo(UserBean userBean) {
		User user = new User();
		user.setEmail(userBean.getEmail());
		user.setPassword(userBean.getPw());

		return user;
	}

}
